<?php
/**
 * Author：晴玖天
 * Creation：2020/2/29 19:44
 * Filename：config.php
 * 数据库配置文件
 */

namespace Medoo\DB;

use DB;
use Medoo\Medoo;

class SQL
{
    /**
     * @return Medoo PDO操作类
     */

    /**
     * @var bool|array
     * 防止数据库重复打开
     */
    private static $NewData = false;

    private static $NewDatas = false;

    /**
     * @return bool|DB
     * DBS 原生DB类调用
     */
    public static function DBS()
    {
        if (self::$NewDatas) {
            return self::$NewDatas;
        }
        global $dbconfig;
        if (empty($dbconfig['host']) || empty($dbconfig['user']) || empty($dbconfig['dbname']) || empty($dbconfig['port']) || empty($dbconfig['pwd'])) {
            //载入最新的
            $dbconfig = self::DBConfig();
        }
        $dbconfig['prefix'] = 'sky_';
        self::$NewDatas = new DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        return self::$NewDatas;
    }

    public static function DB()
    {
        if (self::$NewData) {
            return self::$NewData;
        }
        global $dbconfig;
        if (empty($dbconfig['host']) || empty($dbconfig['user']) || empty($dbconfig['dbname']) || empty($dbconfig['port']) || empty($dbconfig['pwd'])) {
            //载入最新的
            $dbconfig = self::DBConfig();
        }
        $dbconfig['prefix'] = 'sky_';
        self::$NewData = new Medoo([
            'database_type' => 'mysql',
            'database_name' => $dbconfig['dbname'],
            'server' => $dbconfig['host'],
            'username' => $dbconfig['user'],
            'password' => $dbconfig['pwd'],
            'charset' => 'utf8mb4',
            'port' => $dbconfig['port'],
            'prefix' => $dbconfig['prefix'],
        ]);
        return self::$NewData;
    }

    //读取数据库配置
    private static function DBConfig()
    {
        global $dbconfig;
        $Content = file_get_contents(SYSTEM_ROOT . "/deploy.php");
        $pattern = '/\$(.*?)\s*=\s*\[(.*?)\];/is';
        preg_match_all($pattern, $Content, $matches);
        $dbconfigs = [];
        foreach ($matches[1] as $key => $value) {
            $array = $matches[2][$key];
            $pattern = '/\'(.*?)\'\s*=>\s*(.*?),/is';
            preg_match_all($pattern, $array, $match);
            $dbconfigs[$value] = [];
            foreach ($match[1] as $k => $v) {
                $dbconfigs[$value][$v] = trim($match[2][$k], "'");
            }
        }
        $dbconfigs = $dbconfigs['dbconfig'];
        if (empty($dbconfigs['host']) || empty($dbconfigs['user']) || empty($dbconfigs['dbname']) || empty($dbconfigs['port']) || empty($dbconfigs['pwd'])) {
            return $dbconfig;
        }
        return $dbconfigs;
    }
}

